﻿namespace UnityEditorInternal
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading;
    using UnityEditor;

    internal class PostProcessNaclPlayer
    {
        private static bool s_ChromeFailedToLaunch;

        internal static void Launch(BuildTarget target, string targetfile)
        {
            targetfile = Path.GetFullPath(targetfile);
            byte[] buffer = !IsWindows ? Encoding.UTF8.GetBytes(targetfile) : Encoding.Unicode.GetBytes(targetfile);
            byte[] buffer2 = new SHA256Managed().ComputeHash(buffer);
            string str = string.Empty;
            for (int i = 0; i < 0x10; i++)
            {
                str = str + ((char) (0x61 + (buffer2[i] >> 4))) + ((char) (0x61 + (buffer2[i] & 15)));
            }
            string[] textArray1 = new string[] { "chrome-extension://", str, "/", Path.GetFileName(targetfile), "_nacl.html" };
            string str2 = string.Concat(textArray1);
            do
            {
                s_ChromeFailedToLaunch = false;
                Process process = new Process {
                    StartInfo = { FileName = BrowserPath }
                };
                string[] textArray2 = new string[] { " --load-extension=\"", targetfile, "\" \"", str2, "\"" };
                process.StartInfo.Arguments = string.Concat(textArray2);
                process.StartInfo.UseShellExecute = false;
                process.Start();
                Thread.Sleep(0x1388);
                s_ChromeFailedToLaunch = process.HasExited;
                if (s_ChromeFailedToLaunch)
                {
                    if (IsWindows)
                    {
                        s_ChromeFailedToLaunch = EditorUtility.DisplayDialog("Is Google Chrome already running?", "If Chrome is already running, you will only be able to test content which has been installed into Chrome before. If your content is not showing in Chrome, please quit Chrome and try again.", "Try again", "Cancel");
                    }
                    else
                    {
                        s_ChromeFailedToLaunch = EditorUtility.DisplayDialog("Could not start Google Chrome. Is it already running?", "Please quit any running instances of Chrome and try again.", "Try again", "Cancel");
                    }
                }
            }
            while (s_ChromeFailedToLaunch);
        }

        internal static void PostProcess(BuildOptions options, string installPath, string downloadWebplayerUrl, int width, int height)
        {
            PostProcessWebPlayer.PostProcess(options, installPath, downloadWebplayerUrl, width, height);
            string fileName = Path.GetFileName(installPath);
            string str2 = installPath;
            string playbackEngineDirectory = BuildPipeline.GetPlaybackEngineDirectory(BuildTarget.NaCl, BuildOptions.None);
            string str4 = "unity_nacl_files_3.x.x";
            string path = Path.Combine(installPath, str4);
            string from = Path.Combine(playbackEngineDirectory, "unity_nacl_files");
            if (Directory.Exists(path))
            {
                FileUtil.DeleteFileOrDirectory(path);
            }
            FileUtil.CopyFileOrDirectory(from, path);
            StripPhysicsFiles(path, PlayerSettings.stripPhysics);
            string str7 = Path.Combine(playbackEngineDirectory, "template.html");
            string str8 = Path.Combine(str2, fileName + "_nacl.html");
            if (File.Exists(str8))
            {
                FileUtil.DeleteFileOrDirectory(str8);
            }
            FileUtil.CopyFileOrDirectory(str7, str8);
            string str9 = Path.Combine(playbackEngineDirectory, "template.json");
            string str10 = Path.Combine(str2, "manifest.json");
            if (File.Exists(str10))
            {
                FileUtil.DeleteFileOrDirectory(str10);
            }
            FileUtil.CopyFileOrDirectory(str9, str10);
            List<string> list = new List<string> {
                "%UNITY_WIDTH%",
                width.ToString(),
                "%UNITY_HEIGHT%",
                height.ToString(),
                "%UNITY_WEB_NAME%",
                PlayerSettings.productName,
                "%UNITY_WEB_PATH%",
                fileName + ".unity3d",
                "%UNITY_WEB_HTML_PATH%",
                fileName + "_nacl.html",
                "%UNITY_NACL_PARAMETERS%",
                ((options & 1) == null) ? string.Empty : "softexceptions=\"1\"",
                "%UNITY_NACL_ENGINE_PATH%",
                str4,
                "%UNITY_BETA_WARNING%",
                (InternalEditorUtility.IsUnityBeta() == null) ? string.Empty : "\r\n\t\t<p style=\"color: #c00; font-size: small; font-style: italic;\">Built with beta version of Unity.</p>"
            };
            foreach (string str11 in PlayerSettings.templateCustomKeys)
            {
                list.Add("%UNITY_CUSTOM_" + str11.ToUpper() + "%");
                list.Add(PlayerSettings.GetTemplateCustomValue(str11));
            }
            FileUtil.ReplaceText(str8, list.ToArray());
            FileUtil.ReplaceText(str10, list.ToArray());
        }

        private static void StripPhysicsFiles(string path, bool stripPhysics)
        {
            foreach (string str in Directory.GetFiles(path))
            {
                if (str.Contains("_nophysx"))
                {
                    if (stripPhysics)
                    {
                        string str2 = str.Replace("_nophysx", string.Empty);
                        File.Delete(str2);
                        File.Move(str, str2);
                    }
                    else
                    {
                        File.Delete(str);
                    }
                }
            }
            foreach (string str3 in Directory.GetDirectories(path))
            {
                StripPhysicsFiles(str3, stripPhysics);
            }
        }

        private static string BrowserPath
        {
            get
            {
                if (IsWindows)
                {
                    string str = Path.Combine(ProgramFilesx86, Path.Combine("Google", Path.Combine("Chrome", Path.Combine("Application", "chrome.exe"))));
                    if (File.Exists(str))
                    {
                        return str;
                    }
                    string str2 = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
                    if (File.Exists(str2))
                    {
                        return str2;
                    }
                    string str3 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Path.Combine("Google", Path.Combine("Chrome", Path.Combine("Application", "chrome.exe"))));
                    if (!File.Exists(str3))
                    {
                        throw new System.Exception("Cannot find Chrome");
                    }
                    return str3;
                }
                string path = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
                if (!File.Exists(path))
                {
                    throw new System.Exception("Cannot find Chrome");
                }
                return path;
            }
        }

        private static bool IsWindows
        {
            get
            {
                return (Environment.OSVersion.Platform != PlatformID.Unix);
            }
        }

        private static string ProgramFilesx86
        {
            get
            {
                if ((IntPtr.Size != 8) && string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432")))
                {
                    return Environment.GetEnvironmentVariable("ProgramFiles");
                }
                return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
            }
        }
    }
}

